package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.Student;
import com.bwie.common.domain.request.StudentRequest;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.result.Result;
import com.bwie.service.EsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author：ShenJiaFeng
 * @Package：com.bwie.service.impl
 * @Project：zg5_19
 * @name：EsServiceImpl
 * @Date：2024/2/18 14:24
 */
@Service
public class EsServiceImpl implements EsService {
    private final RedisCache redisCache;
    private final RestHighLevelClient client;
    private final HttpServletRequest request;
    public final String INDEX_NAME="student";

    public EsServiceImpl(RedisCache redisCache, RestHighLevelClient client, HttpServletRequest request) {
        this.redisCache = redisCache;
        this.client = client;
        this.request = request;
    }

    @Override
    public Result<List<Student>> esList(StudentRequest studentRequest) {
//        User user = redisCache.getCacheObject(
//                TokenConstants.LOGIN_TOKEN_KEY + request.getHeader(JwtConstants.USER_KEY)
//        );

        ArrayList<Student> studentArrayList = new ArrayList<>();

        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (studentRequest.getStudentName() != null && !studentRequest.getStudentName().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("studentName",studentRequest.getStudentName()));
        }

//        高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("studentName")
                .postTags("<color=\"color:red\">")
                .preTags("</color>");


//        分页
        searchSourceBuilder.from((studentRequest.getPageNum()-1)*studentRequest.getPageSize());
        searchSourceBuilder.size(studentRequest.getPageSize());

        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                Student student = JSONObject.parseObject(sourceAsString, Student.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField studentName = highlightFields.get("studentName");
                if (studentName!=null){
                    StringBuilder stringBuilder = new StringBuilder();
                    for (Text fragment : studentName.getFragments()) {
                        stringBuilder.append(fragment.toString());
                        student.setStudentName(stringBuilder.toString());
                    }
                }
                studentArrayList.add(student);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.success(studentArrayList,"es列表");

//        ArrayList<Student> studentArrayList = new ArrayList<>();
//
//        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
//
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//
//        if (studentRequest.getStudentName()!=null && !studentRequest.getStudentName().isEmpty()){
//            boolQueryBuilder.must(QueryBuilders.matchQuery("studentName",studentRequest.getStudentName()));
//        }
//
//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.field("studentName")
//                .preTags("<color=\"color:red\">")
//                .postTags("</span>");
//        searchSourceBuilder.from((studentRequest.getPageNum()-1)*studentRequest.getPageSize());
//        searchSourceBuilder.size(studentRequest.getPageSize());
////        高亮请求
//        searchSourceBuilder.highlighter(highlightBuilder);
////        布尔条件查询
//        searchSourceBuilder.query(boolQueryBuilder);
//        searchRequest.source(searchSourceBuilder);
//
//        try {
//            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//            SearchHits hits = response.getHits();
//            long value = hits.getTotalHits().value;
//            for (SearchHit hit : hits.getHits()) {
//                String sourceAsString = hit.getSourceAsString();
//                Student student = JSONObject.parseObject(sourceAsString, Student.class);
//                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//                HighlightField studentName = highlightFields.get("studentName");
//                if (studentName !=null) {
//                    StringBuilder stringBuilder = new StringBuilder();
//                    for (Text fragment : studentName.getFragments()) {
//                        stringBuilder.append(fragment.toString());
//                        student.setStudentName(stringBuilder.toString());
//                    }
//                }
//                studentArrayList.add(student);
//
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//
//        return Result.success(studentArrayList,"列表");
    }
}
